package com.my.job.util;

import java.lang.reflect.Method;

import org.springframework.util.ReflectionUtils;

import com.my.job.common.Page;


public class PageUtils
{
	public static <T> Page<T> setPageToExample(Page<T> page, Object example)
	{
		if (example == null )
		{
			throw new IllegalArgumentException("the 'example' argument can't be null");
		}
		
		if (page == null)
		{
			page = new Page<T>(10);
		}

		try
		{
			Method setLimitStart = example.getClass().getMethod("setLimitStart", int.class);
			ReflectionUtils.invokeMethod(setLimitStart, example, page.getPageSize() * (page.getPageNo() - 1));

			Method setLimitEnd = example.getClass().getMethod("setLimitEnd", int.class);
			ReflectionUtils.invokeMethod(setLimitEnd, example, page.getPageSize());

			if (page.getOrderBy() != null)
			{
				Method setOrderByClause = example.getClass().getMethod("setOrderByClause", String.class);
				ReflectionUtils.invokeMethod(setOrderByClause, example,page.getOrderBy());
			}
		}
		catch (NoSuchMethodException e)
		{
			throw new IllegalStateException("Method not found: " + e.getMessage());
		}
		return page;
	}
}
